package org.example;

import org.apache.catalina.Context;
import org.apache.catalina.WebResourceRoot;
import org.apache.catalina.startup.Tomcat;
import org.apache.catalina.webresources.DirResourceSet;
import org.apache.catalina.webresources.StandardRoot;

import java.io.File;

/**
 * 主启动类
 * @author xw
 */
public class SpringApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringApplication.class);
    }

    private static void run(Class<SpringApplication> springApplicationClass) {
        try {
            Tomcat tomcat = new Tomcat();
            tomcat.setPort(8080);

            // 获取项目编译后的class 路径
            String path = springApplicationClass.getResource("/").getPath();
            // 获取webapp 文件
            String filePath = new File("src/main/webapp").getAbsolutePath();
            // 然后将webapp下的项目添加至tomcat的context容器（context对应一个运行的项目）
            Context context = tomcat.addWebapp("/", filePath);
            WebResourceRoot webResource = new StandardRoot(context);
            webResource.addPreResources(new DirResourceSet(webResource, "/WEB-INF/classes", path, "/"));

            // tomcat启动
            tomcat.start();
            tomcat.getServer().await();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
